package top.chenyaohua.nginx.clojure;

import com.google.gson.Gson;
import nginx.clojure.Configurable;
import nginx.clojure.NginxClojureRT;
import nginx.clojure.NginxHttpServerChannel;
import nginx.clojure.NginxRequest;
import nginx.clojure.java.ArrayMap;
import nginx.clojure.java.NginxJavaRequest;
import nginx.clojure.java.NginxJavaRingHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static nginx.clojure.MiniConstants.*;


public class NginxSpringHandlerWrapper implements NginxJavaRingHandler, Configurable  {

    private  RouterService service;

    @Override
    public Object[] invoke(Map<String, Object> map) throws IOException {
        //转换为NginxJavaRequest类型
        NginxJavaRequest nginxJavaRequest = (NginxJavaRequest) map;
        //http请求头信息
        Map<String,Object> headers = (Map) nginxJavaRequest.get(HEADERS);
        //获取请求头中携带的token信息
        String token = (String) headers.get("token");
        //打印日志
        NginxClojureRT.getLog().error("token:"+token);

        String byToken = service.getIpByToken(token);

        Map<String, String> params = new HashMap<>();
        params.put("token", byToken);

        return new Object[] {
            NGX_HTTP_OK,
            ArrayMap.create(CONTENT_TYPE,  "application/json"),
            new Gson().toJson(params)
        } ;
    }

    @Override
    public void config(Map<String, String> map) {

        String routerService = map.get("router_service");
        NginxClojureRT.getLog().error("routerService:"+routerService);

        service = (RouterService) NginxClojureInitHandler.getBean(routerService);

    }
}
